﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using PaperSystem.Models;
using Webdiyer.WebControls.Mvc;

namespace PaperSystem.Controllers
{
    public class QuestionController : Controller
    {
        //
        // GET: /Question/
        QuestionRepository _questionRepository;
        PublicRepository _publicRepository;
        public QuestionController()
        {
            _questionRepository = new QuestionRepository();
            _publicRepository = new PublicRepository();
        }

        //显示题目基本信息
        public ActionResult QuestionList(QuestionQuery info,int? page)
        {
            //验证cookie
            if (Request.Cookies[FormsAuthentication.FormsCookieName] == null)
            {
                TempData["errorMessage"] = "请先登录，再操作";
                return RedirectToAction("Index", "Login");
            }
            else
            {
                string userId = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                string role = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).UserData;
                if (role != "教师")
                {
                    TempData["errorMessage"] = "用户角色改变，请再登录";
                    return RedirectToAction("Index", "Login");
                }
                ViewData["userName"] = _publicRepository.UserName(userId, role);
            }//end 验证cookie
            //TODO：还要适当调整info内容，再根据info确定要哪些信息
            List<QuestionList> questionList = _questionRepository.GetQuestionList(info);
            ViewData["course"] = _questionRepository.GetCourse();
            ViewData["type"] = _questionRepository.GetType();
            //用于分页
            PagedList<QuestionList> plist = new PagedList<QuestionList>(questionList, page ?? 1, 30);
            return View("QuestionList", plist);
        }

        //新增题目（显示）
        public ActionResult QuestionAdd()
        {
            //验证cookie
            if (Request.Cookies[FormsAuthentication.FormsCookieName] == null)
            {
                TempData["errorMessage"] = "请先登录，再操作";
                return RedirectToAction("Index", "Login");
            }
            else
            {
                string userId = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                string role = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).UserData;
                if (role != "教师")
                {
                    TempData["errorMessage"] = "用户角色改变，请再登录";
                    return RedirectToAction("Index", "Login");
                }
                ViewData["userName"] = _publicRepository.UserName(userId, role);
            }//end 验证cookie
            ViewData["course"] = _questionRepository.GetCourse();
            ViewData["type"] = _questionRepository.GetType();
            return View();
        }

        //新增题目（提交）
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult QuestionAdd(NewExQuestion exQuestion, NewInQuestion[] inQuestion)
        {
            //验证cookie
            if (Request.Cookies[FormsAuthentication.FormsCookieName] == null)
            {
                TempData["errorMessage"] = "请先登录，再操作";
                return RedirectToAction("Index", "Login");
            }
            else
            {
                string userId = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                string role = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).UserData;
                if (role != "教师")
                {
                    TempData["errorMessage"] = "用户角色改变，请再登录";
                    return RedirectToAction("Index", "Login");
                }
                ViewData["userName"] = _publicRepository.UserName(userId, role);
                ViewData["userId"] = userId;
            }//end 验证cookie
            exQuestion.creatorId = ViewData["userId"].ToString();
            exQuestion.time = DateTime.Today;
            if (_questionRepository.InsertQuestion(exQuestion, inQuestion))
            {
                TempData["begin_message"] = "添加成功";
            }
            else
            {
                TempData["begin_message"] = "添加失败";
            }
            //返回添加页面
            ViewData["course"] = _questionRepository.GetCourse();
            ViewData["type"] = _questionRepository.GetType();
            return View();
        }

        //删除题目（提交）
        [HttpPost]
        public ActionResult QuestionDelete(string eid, QuestionQuery info)
        {
            //验证cookie
            if (Request.Cookies[FormsAuthentication.FormsCookieName] == null)
            {
                TempData["errorMessage"] = "请先登录，再操作";
                return RedirectToAction("Index", "Login");
            }
            else
            {
                string userId = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                string role = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).UserData;
                if (role != "教师")
                {
                    TempData["errorMessage"] = "用户角色改变，请再登录";
                    return RedirectToAction("Index", "Login");
                }
                ViewData["userName"] = _publicRepository.UserName(userId, role);
            }//end 验证cookie
            if (_questionRepository.DeleteQuestion(eid))
            {
                TempData["begin_message"] = "删除成功";
            }
            else
            {
                TempData["begin_message"] = "删除失败";
            }
            //return QuestionList(info,null);
            return RedirectToAction("QuestionList","Question",info);
        }

        //修改题目（显示）
        public ActionResult QuestionUpdate(string eid)
        {
            //验证cookie
            if (Request.Cookies[FormsAuthentication.FormsCookieName] == null)
            {
                TempData["errorMessage"] = "请先登录，再操作";
                return RedirectToAction("Index", "Login");
            }
            else
            {
                string userId = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                string role = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).UserData;
                if (role != "教师")
                {
                    TempData["errorMessage"] = "用户角色改变，请再登录";
                    return RedirectToAction("Index", "Login");
                }
                ViewData["userName"] = _publicRepository.UserName(userId, role);
            }//end 验证cookie
            //验证eid是否合法
            int id = -1;
            if (eid == null || eid == "" || !int.TryParse(eid, out id))
            {
                return RedirectToAction("QuestionList");
            }//end 验证eid是否合法

            UpdateQuestion question = _questionRepository.GetUpdateQuestion(id);
            //返回View页面
            ViewData["course"] = _questionRepository.GetCourse(question.course);
            ViewData["type"] = _questionRepository.GetType(question.type);
            return View(question);
        }

        //修改题目（提交）
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult QuestionUpdate(UpdateQuestion question)
        {
            //验证cookie
            if (Request.Cookies[FormsAuthentication.FormsCookieName] == null)
            {
                TempData["errorMessage"] = "请先登录，再操作";
                return RedirectToAction("Index", "Login");
            }
            else
            {
                string userId = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                string role = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).UserData;
                if (role != "教师")
                {
                    TempData["errorMessage"] = "用户角色改变，请再登录";
                    return RedirectToAction("Index", "Login");
                }
                ViewData["userName"] = _publicRepository.UserName(userId, role);
            }//end 验证cookie
            if (_questionRepository.UpdateQuestion(question))
            {
                TempData["begin_message"] = "修改成功";
            }
            else
            {
                TempData["begin_message"] = "修改失败";
            }
            //返回View页面
            //return QuestionList(null,null);这样用刷新不到网址
            return RedirectToAction("QuestionList");
        }

        //添加新课程
        [HttpPost]
        public ContentResult CourseAdd(string newCourse)
        {
            if (_questionRepository.AddCourse(newCourse))
            {
                return Content("添加成功");
            }
            else
            {
                return Content("添加失败");
            }
        }
    }
}
